package com.czy.controller;

import com.czy.common.Result;
import com.czy.model.Account;
import com.czy.service.AccountService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @Author: czy
 * @Date: 2019/11/8 13:57
 */
@Controller
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;

    /**
     * 登录
     * @param map
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result login(@RequestBody Map<String,Object> map, Model model, HttpServletRequest request){
        String userName = (String)map.get("userName");
        String password = (String) map.get("password");
        String code = (String)map.get("code");
        if (StringUtils.isBlank(code)){
            return Result.fail("请输入验证码!");
        }
        String verificationImage = (String)request.getSession().getAttribute("verificationImage");
        if (StringUtils.isBlank(verificationImage) || !verificationImage.equalsIgnoreCase(code)){
            return Result.fail("验证码错误!");
        }
        return accountService.login(userName,password);
    }

    /**
     * 注册
     * @param account
     * @return
     */
    @ResponseBody
    @PostMapping("/register")
    public Result register(@RequestBody Account account,HttpServletRequest request){
        String code = account.getCode();
        String verificationImage = (String)request.getSession().getAttribute("verificationImage");
        if (!verificationImage.equalsIgnoreCase(code)){
            return Result.fail("验证码错误!");
        }
        return accountService.insert(account);
    }


    /**
     * 激活
     * @param activiteCode
     * @return
     */
    @GetMapping("/activited")
    public String activited(@RequestParam String activiteCode, HttpServletResponse response,Model model) throws IOException {
        if (activiteCode == null) {
            model.addAttribute("message","未传入激活码");
            return "email.html";
        }
        //根据激活码查找用户
        Integer userId = accountService.findAccountByActivitieCode(activiteCode);
        if (userId == null) {
            model.addAttribute("message","激活码无效");
            return "email.html";
        }
        //更新用户激活状态
        Integer re = accountService.updateAccountById(userId);
        String message;
        if (re > 0) {
            model.addAttribute("message","激活成功");
            model.addAttribute("result",1);
            return "email.html";
        } else {
            model.addAttribute("message","激活失败,请联系管理员");
            return "email.html";
        }
    }
}
